# 一、数据处理
from sklearn.svm import SVC
from sklearn.svm import SVR

from sklearn.datasets import load_breast_cancer	
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
import numpy as np
import pandas as pd
x,y=load_breast_cancer().data,load_breast_cancer().target
print(x.shape)
print(x)



# 二、使用函数训练模型
#数据标准化处理
from sklearn.preprocessing import StandardScaler
x=StandardScaler().fit_transform(x)
print(x)

#分割数据集
from sklearn.metrics import accuracy_score
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3,random_state=420)
Kernel=["linear","poly","rbf","sigmoid"]
for kernel in Kernel:
   model=SVC(kernel=kernel,gamma="auto",degree=1)
   model.fit(x_train,y_train)
   pred=model.predict(x_test)
   ac=accuracy_score(y_test,pred)
   print(f"选择{kernel}核函数时，模型的预测准确率为: {ac}")


# 三、多项式核函数参数的调节
#     1、数据处理
from sklearn.datasets import load_breast_cancer					        #导入肺癌数据集
from sklearn.svm import SVC                                             #导入支持向量机分类模块
from sklearn.model_selection import train_test_split
import numpy as np
from sklearn.preprocessing import StandardScaler

x,y=load_breast_cancer().data,load_breast_cancer().target 
x=StandardScaler().fit_transform(x)

#      2、训练模型
from sklearn.model_selection import StratifiedShuffleSplit              #导入分层抽样方法
from sklearn.model_selection import GridSearchCV		                #导入网格搜索方法


gamma_range=np.logspace(-10,1,20)
coef0_range=np.linspace(0,5,10)
param_grid=dict(gamma=gamma_range,coef0=coef0_range)
cv=StratifiedShuffleSplit(n_splits=5,test_size=0.3,random_state=420)    #对样本进行分层抽样
grid=GridSearchCV(SVC(kernel="poly",degree=1),
param_grid=param_grid,cv=cv)	                                        #使用网格搜索法寻找参数的最优值
grid.fit(x,y)


print(f"最优参数值为：{grid.best_params_}")
print(f"选取该参数值时，模型的预测准确率为：{grid.best_score_}")


# 四、使用高斯径向基核函数进行参数的调节
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt


x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3,random_state=420)					#分割数据集
score=[]
gamma_range=np.logspace(-10,1,50)
for i in gamma_range:
    model=SVC(kernel='rbf',gamma=i)
    model.fit(x_train,y_train)
    pred=model.predict(x_test)
    ac=accuracy_score(y_test,pred)
    score.append(ac)


plt.plot(gamma_range,score)
plt.show()

print(f"参数gamma的最优值为：{gamma_range[score.index(max(score))]}")
print(f"选取该参数值时，模型的预测准确率为：{max(score)}")
